package propagator

import (
	"net/http"
	"server/framework/web/session"
	"time"
)

type Propagator struct {
	cookieName string
	duration   time.Duration
}

func (p *Propagator) Extract(r *http.Request) (string, error) {
	ck, err := r.Cookie(p.cookieName)
	if err != nil {
		return "", err
	}
	return ck.Value, nil
}

func (p *Propagator) Inject(w http.ResponseWriter, id string) error {
	http.SetCookie(w, &http.Cookie{
		Name:     p.cookieName,
		Value:    id,
		Path:     "/",
		HttpOnly: true,
		Expires:  time.Now().Add(p.duration),
	})

	return nil
}

func (p *Propagator) Delete(w http.ResponseWriter) error {
	http.SetCookie(w, &http.Cookie{
		Name:   p.cookieName,
		MaxAge: -1,
	})
	return nil
}

func NewPropagator(cookieName string, duration time.Duration) *Propagator {
	return &Propagator{
		cookieName: cookieName,
		duration:   duration,
	}
}

var _ session.Propagator = &Propagator{}
